/**
 * 
 */
package org.jboss.minstaller


import org.jboss.minstaller.util.*;

/**
 * @author jjeon@redhat.com
 *
 */
public class Installer {
    def ServerConfig serverConfig;
    
    def ServerPrepareStage serverPrepareStage;
    def ServerPostInstallStage serverPostInstallStage;
    
    def WebServer webServer;

    public void checkServers() {
        println "Check Servers : ";
        println "   1. Checking SSH Service is available";
        println "   2. Checking wget is available";
        println "   3. Checking FTP Service is available";
        
        println "Now checking JBoss Servers....";
        println serverConfig;
        
        for ( i in 0..serverConfig.getServersSize()-1 ) {
            def server = serverConfig.servers.server[i];
            def serverip = server.ip.text();
            
            println "======================================================================";
            println "Target JBoss Server : " + server.name.text() + " ("+ serverip + ")";
            println "======================================================================";
            
            println "   > 1. Checking SSH Service is available";
            println "   > >  Checking JBoss directory have permission to " + serverConfig.getServerUserid();
            // mkdir for JBoss Install
            SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                    "mkdir -p " + serverConfig.getJBossInstallDir());

            println "   2. Checking wget is available";
            // wget test
            SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                    serverConfig.getJBossInstallDir(),
                    "wget http://" + serverConfig.getWgethostPort() + "/resources/test/test.txt" ); 
            
            println "   3. Checking SSH Service is available";                    
            // upload JBoss port-binding.xml files 
            println " > FTP upload test ...";
            FtpUtil.ftpCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                            serverConfig.getJBossInstallDir(), "./resources/test" );  

            println "   4. Cleanup test file";                    
            SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                            serverConfig.getJBossInstallDir(),
                            "rm test.txt*" ); 
            
        }       
    }    

    
    public Installer(conf_file) {
        serverConfig = new ServerConfig(conf_file);
        serverPrepareStage = new ServerPrepareStage( serverConfig );
        serverPostInstallStage = new ServerPostInstallStage( serverConfig );
        
        webServer = new WebServer(serverConfig);
        webServer.startServer();
    }
    
    void serverPrepare(server) {
        
    }
    
    public void installJBossBinary() {
        println "Installing JBoss Binary....";
        println serverConfig;
        
        for ( i in 0..serverConfig.getServersSize()-1 ) {
            def server = serverConfig.servers.server[i];
            def serverip = server.ip.text();
            
            println "======================================================================";
            println "Install JBoss Server : " + server.name.text() + " ("+ serverip + ")";
            println "======================================================================";
            
            // mkdir for JBoss Install
            SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                    "mkdir -p " + serverConfig.getJBossInstallDir());
          
            // wget JBoss Binary
            SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                    serverConfig.getJBossInstallDir(),
                    "wget http://" + serverConfig.getWgethostPort() + "/resources/jbossas/" + serverConfig.getJBossVersion() + "/binary/" + serverConfig.getJBossVersion() + ".zip" ); 
            
            // unzip for JBoss
            SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                    serverConfig.getJBossInstallDir(),
                    "unzip -o " + serverConfig.getJBossVersion() + ".zip" );            

            // chown of dirs            
            SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                            serverConfig.getJBossInstallDir(),
                            "chown -R " + serverConfig.getServerUserid() + "." + serverConfig.getServerUserid() + " *" );            
           
            // upload JBoss port-binding.xml files 
            println " > upload jboss port-binding.xml ...";
            FtpUtil.ftpCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                            serverConfig.getServerJBossHome(), "./resources/jbossas/server.conf" );  
            
        }       
    }    
    
    public void installJBossInstance() {
        println "Start B29 Installer....";
        println serverConfig;
        
        for ( i in 0..serverConfig.getServersSize()-1 ) {
            def server = serverConfig.servers.server[i];
            def serverip = server.ip.text();
            
            println "==================================================================================";
            println "   Install Server : " + server.name.text() + " ("+ serverip + ")";
            println "==================================================================================";    		
            // mkdir for JBoss domains directory
            SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                    "mkdir -p " + serverConfig.getServerServerHome());
            
            for ( j in 0..serverConfig.getJBossServersSize(server)-1 )
            {
                def jbossServerName = server.jbossservers.jbossserver[j].servername.text();
                println "======================================================================";
                println "        JBoss Instance : " + jbossServerName;
                println "======================================================================";
                
                // replace strings...
                println " > generate JBoss instance files...";
                def jbossServer = server.jbossservers.jbossserver[j];
                serverPrepareStage.prepare( j, serverip, jbossServer );
                
                // mkdir for JBoss server instance directory
                println " > make JBoss instance directory on server...";
                SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                        "mkdir -p " + serverConfig.getServerServerHome() + "/" + jbossServerName );
                
                
                // copy jboss-as/server/production to domains
                println " > copy JBoss production instance on server...";
                SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                        "cp -R " + serverConfig.getServerJBossHome() + "/server/" + serverConfig.getServerType() + "/* " 
                        + serverConfig.getServerServerHome() + "/" + jbossServerName );
                
                // upload JBoss config files , remote / local
                println " > copy JBoss production instance...";
                FtpUtil.ftpCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                        serverConfig.getServerServerHome() + "/" + jbossServerName, "./working" );  
                
                // execute serverconfig.sh in domains
                println " > copy JBoss serverconfig.sh...";
                SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                        serverConfig.getServerServerHome() + "/" + jbossServerName, 
                        "chmod u+x *.sh");                
                
                SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                        serverConfig.getServerServerHome() + "/" + jbossServerName, 
                        "./serverconfig.sh");
                
                // mkdir user's apphome directory
                println " > make instance's WebApp Directory...";
                SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                        "mkdir -p " + serverConfig.getAppHome() + "/" + server.jbossservers.jbossserver[j].webapp );
                
                // upload JBoss application files , remote / local
                println " > upload sample session.war application...";
                FtpUtil.ftpCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                        serverConfig.getAppHome() + "/" + server.jbossservers.jbossserver[j].webapp, "./resources/jbossas/apps" );  
                
                println "======================================================================";
                println " *****  " + server.jbossservers.jbossserver[j].servername.text() + " finished ***** ";
                println "======================================================================";
            }
            println "==================================================================================";
            println " **** Server : " + server.name.text() + " ("+ serverip + ") finished *****";
            println "==================================================================================";           
        }    	
    }
    
    public void updateJBossInstance() {
        println "Start JB29 Installer....";
        println serverConfig;
        
        for ( i in 0..serverConfig.getServersSize()-1 ) {
            def server = serverConfig.servers.server[i];
            def serverip = server.ip.text();
            
            println "==================================================================================";
            println "   Install Server : " + server.name.text() + " ("+ serverip + ")";
            println "==================================================================================";           
            // mkdir for JBoss domains directory
            SSHUtil.sshCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                    "mkdir -p " + serverConfig.getServerServerHome());
            
            for ( j in 0..serverConfig.getJBossServersSize(server)-1 )
            {
                def jbossServerName = server.jbossservers.jbossserver[j].servername.text();
                println "======================================================================";
                println "        JBoss Instance : " + jbossServerName;
                println "======================================================================";
                
                // replace strings...
                println " > generate JBoss instance files...";
                def jbossServer = server.jbossservers.jbossserver[j];
                serverPrepareStage.prepare( j, serverip, jbossServer );            
                
                // upload JBoss config files , remote / local
                println " > copy JBoss production instance...";
                FtpUtil.ftpCommand( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(), 
                        serverConfig.getServerServerHome() + "/" + jbossServerName, "./working" );  
                
                // execute serverconfig.sh in domains
                println " > copy JBoss serverconfig.sh...";
                SSHUtil.sshCommandInDir( serverip, serverConfig.getServerUserid(), serverConfig.getServerPasswd(),
                        serverConfig.getServerServerHome() + "/" + jbossServerName, 
                        "chmod u+x *.sh");                
                
                println "======================================================================";
                println " *****  " + server.jbossservers.jbossserver[j].servername.text() + " finished ***** ";
                println "======================================================================";
            }
            println "==================================================================================";
            println " **** Server : " + server.name.text() + " ("+ serverip + ") finished *****";
            println "==================================================================================";      
        }       
    }
    
    
    // TODO : apache workers.properties
    
    public static void main(args)
    {
        
        if ( args.size() < 2 ) {
            println("")
            println("JB29Installer - JBoss Massive Installer ^^)")
            println("")
            println("Usage : java org.jboss.minstaller.Installer <configFile> <command>")
            println("")
            println("avaliable commands are ...")
            println("       check   : check servers")
            println("       install : install binary & setup jboss instances")
            println("       update  : update configuration of jboss instances")
            println("")
            return;
        }
        
        def configFile = args[0];
        def commands = args[1];
        
        Installer installer = new Installer(configFile);        
        
        if( commands == "update" ) {
            installer.updateJBossInstance();
        } else if ( commands == "check" ) {
            installer.checkServers();
        } else if ( commands == "install" ) {
            installer.installJBossBinary();
            installer.installJBossInstance();
        } else {
            println( "Unknown command : only update and install are supported commands")
        }
        System.exit(-1);
    }
}
